/**
 * 数据缓存管理器测试
 * 
 * 用途：测试DataCacheManager的数据覆盖机制和缓存功能
 * 方法：创建模拟数据，验证时间戳覆盖逻辑和缓存管理功能
 * 原理：通过单元测试确保数据覆盖机制按预期工作
 */
package com.example.brain_wave.test

import com.example.brain_wave.bluetooth.cache.DataCacheManager
import com.example.brain_wave.api.model.TabletBrainWaveResponse
import org.junit.Test
import org.junit.Assert.*
import org.junit.Before
import android.content.Context
import androidx.test.core.app.ApplicationProvider

class DataCacheManagerTest {
    
    private lateinit var cacheManager: DataCacheManager
    
    @Before
    fun setUp() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        cacheManager = DataCacheManager(context)
    }
    
    @Test
    fun testDataOverwrite() {
        // 创建初始数据
        val timestamp = System.currentTimeMillis()
        val initialResponse = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = timestamp,
            receivedDataPoints = 256,
            sleepStage = "light_sleep",
            confidence = 0.8f,
            frequencyBands = null,
            analysisDurationMs = 1000,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        // 处理初始数据
        cacheManager.processServerResponse(initialResponse)
        
        // 验证初始数据
        val cachedData = cacheManager.getAllDataPoints()
        assertEquals(1, cachedData.size)
        assertEquals("light_sleep", cachedData[0].sleepStage)
        assertEquals(0.8f, cachedData[0].confidence, 0.01f)
        
        // 创建相同时间戳的新数据（应该覆盖旧数据）
        val updatedResponse = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = timestamp, // 相同时间戳
            receivedDataPoints = 256,
            sleepStage = "deep_sleep", // 不同的值
            confidence = 0.9f, // 不同的值
            frequencyBands = null,
            analysisDurationMs = 1200,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        // 处理更新数据
        cacheManager.processServerResponse(updatedResponse)
        
        // 验证数据被覆盖
        val updatedCachedData = cacheManager.getAllDataPoints()
        assertEquals(1, updatedCachedData.size) // 仍然只有一个数据点
        assertEquals("deep_sleep", updatedCachedData[0].sleepStage) // 数据已更新
        assertEquals(0.9f, updatedCachedData[0].confidence, 0.01f) // 数据已更新
    }
    
    @Test
    fun testMultipleDataPoints() {
        val baseTime = System.currentTimeMillis()
        
        // 创建多个不同时间戳的响应
        val response1 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime,
            receivedDataPoints = 256,
            sleepStage = "wake",
            confidence = 0.7f,
            frequencyBands = null,
            analysisDurationMs = 1000,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val response2 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 1000,
            receivedDataPoints = 256,
            sleepStage = "light_sleep",
            confidence = 0.8f,
            frequencyBands = null,
            analysisDurationMs = 1100,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val response3 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 2000,
            receivedDataPoints = 256,
            sleepStage = "deep_sleep",
            confidence = 0.9f,
            frequencyBands = null,
            analysisDurationMs = 1200,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        // 处理数据
        cacheManager.processServerResponse(response1)
        cacheManager.processServerResponse(response2)
        cacheManager.processServerResponse(response3)
        
        // 验证所有数据都被缓存
        val cachedData = cacheManager.getAllDataPoints()
        assertEquals(3, cachedData.size)
        
        // 验证数据按时间戳排序
        assertEquals(baseTime, cachedData[0].timestamp)
        assertEquals(baseTime + 1000, cachedData[1].timestamp)
        assertEquals(baseTime + 2000, cachedData[2].timestamp)
        
        // 验证数据值
        assertEquals("wake", cachedData[0].sleepStage)
        assertEquals("light_sleep", cachedData[1].sleepStage)
        assertEquals("deep_sleep", cachedData[2].sleepStage)
    }
    
    @Test
    fun testPartialDataOverwrite() {
        val baseTime = System.currentTimeMillis()
        
        // 创建初始响应
        val initialResponse1 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime,
            receivedDataPoints = 256,
            sleepStage = "wake",
            confidence = 0.7f,
            frequencyBands = null,
            analysisDurationMs = 1000,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val initialResponse2 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 1000,
            receivedDataPoints = 256,
            sleepStage = "light_sleep",
            confidence = 0.8f,
            frequencyBands = null,
            analysisDurationMs = 1100,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        cacheManager.processServerResponse(initialResponse1)
        cacheManager.processServerResponse(initialResponse2)
        
        // 创建部分更新数据（覆盖第一个响应，并添加新的响应）
        val updatedResponse1 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime, // 覆盖第一个响应
            receivedDataPoints = 256,
            sleepStage = "deep_sleep", // 更新睡眠阶段
            confidence = 0.9f, // 更新置信度
            frequencyBands = null,
            analysisDurationMs = 1200,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val newResponse = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 2000, // 新的响应
            receivedDataPoints = 256,
            sleepStage = "rem",
            confidence = 0.85f,
            frequencyBands = null,
            analysisDurationMs = 1300,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        cacheManager.processServerResponse(updatedResponse1)
        cacheManager.processServerResponse(newResponse)
        
        // 验证结果
        val finalData = cacheManager.getAllDataPoints()
        assertEquals(3, finalData.size) // 应该有3个响应
        
        // 验证第一个响应被更新
        assertEquals("deep_sleep", finalData[0].sleepStage)
        assertEquals(0.9f, finalData[0].confidence, 0.01f)
        
        // 验证第二个响应保持不变
        assertEquals("light_sleep", finalData[1].sleepStage)
        assertEquals(0.8f, finalData[1].confidence, 0.01f)
        
        // 验证新响应被添加
        assertEquals("rem", finalData[2].sleepStage)
        assertEquals(0.85f, finalData[2].confidence, 0.01f)
    }
    
    @Test
    fun testCacheSize() {
        // 测试缓存大小限制
        cacheManager.setCacheConfig(maxSize = 2, maxTimeMs = 300_000L)
        
        val baseTime = System.currentTimeMillis()
        
        // 创建3个响应（超过缓存限制）
        val response1 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime,
            receivedDataPoints = 256,
            sleepStage = "wake",
            confidence = 0.7f,
            frequencyBands = null,
            analysisDurationMs = 1000,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val response2 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 1000,
            receivedDataPoints = 256,
            sleepStage = "light_sleep",
            confidence = 0.8f,
            frequencyBands = null,
            analysisDurationMs = 1100,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        val response3 = TabletBrainWaveResponse(
            success = true,
            message = "数据分析完成",
            sessionId = "test_session",
            timestamp = baseTime + 2000,
            receivedDataPoints = 256,
            sleepStage = "deep_sleep",
            confidence = 0.9f,
            frequencyBands = null,
            analysisDurationMs = 1200,
            bufferSize = 16809,
            yasaAvailable = true
        )
        
        // 处理响应
        cacheManager.processServerResponse(response1)
        cacheManager.processServerResponse(response2)
        cacheManager.processServerResponse(response3)
        
        // 验证缓存大小限制生效（应该只保留最新的2个响应）
        val cachedData = cacheManager.getAllDataPoints()
        assertEquals(2, cachedData.size)
        
        // 验证保留的是最新的两个响应
        assertEquals(baseTime + 1000, cachedData[0].timestamp)
        assertEquals(baseTime + 2000, cachedData[1].timestamp)
        assertEquals("light_sleep", cachedData[0].sleepStage)
        assertEquals("deep_sleep", cachedData[1].sleepStage)
    }
}